package com.sx.pipeline.app.model

import android.app.Application
import android.net.Uri
import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.callback.NavCallback
import com.blankj.utilcode.util.ToastUtils
import com.sx.mvvmlibs.base.BaseViewModel
import com.sx.mvvmlibs.event.SingleLiveEvent
import com.sx.mvvmlibs.http.CommonObserver
import com.sx.mvvmlibs.utils.Logs
import com.sx.mvvmlibs.utils.RxThreadHelper
import com.sx.pipeline.arouth.RouteManager
import com.sx.pipeline.repos.AppRepos
import com.sx.pipeline.repos.http.req.ModifyPwdDTO
import com.sx.pipeline.repos.http.res.*
import com.sx.pipeline.ui.chat.detail.ConversationActivity
import com.tencent.connect.UserInfo
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.observers.DisposableObserver
import io.rong.imkit.RongIM
import io.rong.imkit.userinfo.UserDataProvider
import io.rong.imkit.utils.RouteUtils
import io.rong.imlib.RongIMClient
import java.io.File


/**
 * @Author: YY
 * @Date: 2022/4/5
 * @Description: 二次封装 ViewModel，项目的VM继承于此基类
 */
open class CYBaseViewModel(app: Application) :
    BaseViewModel<AppRepos>(app, Injection.provideRepository()) {

    // 验证码状态
    val smsCodeEvent: SingleLiveEvent<Void> = SingleLiveEvent()

    /**
     * 获取验证码
     */
    fun sendSmsCode(phone: String, smsType: Int) {
        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showShort("请输入手机号")
            return
        }
        if (phone.length < 11) {
            ToastUtils.showShort("手机号格式错误")
            return
        }
        addSubscribe(
            mModel.sendSmsCode(phone, smsType)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<Boolean, BaseViewModel<*>>(
                    this, true
                ) {
                    override fun onSuccess() {
                        ToastUtils.showShort("获取验证码成功")
                        smsCodeEvent.call()
                    }

                    override fun onResult(result: Boolean) {

                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort("获取验证码失败")
                    }
                })
        )
    }

    /**
     * 获取单位下所有联系人
     */
    val taskContactListEvent: SingleLiveEvent<List<TaskContactVo>> = SingleLiveEvent()

    // 现场负责人
    val taskContactData: MutableList<String> = ArrayList()
    val taskContactPhoneData: MutableList<String> = ArrayList()

    fun getContacts() {
        addSubscribe(
            mModel.getContacts()
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<List<TaskContactVo>, BaseViewModel<*>>
                    (this, true) {

                    override fun onResult(result: List<TaskContactVo>) {
                        taskContactListEvent.postValue(result)
                        for (data in result) {
                            taskContactData.add(data.contacts)
                            taskContactPhoneData.add(data.contactsPhone)
                        }
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort("$msg")

                    }
                })
        )
    }


    /**
     * 获取登录单位信息
     */
    val userUnitEvent: SingleLiveEvent<UserUnitVo> = SingleLiveEvent()
    fun getUserUnit() {
        addSubscribe(
            mModel.getUserUnit()
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<UserUnitVo, BaseViewModel<*>>
                    (this, true) {

                    override fun onResult(result: UserUnitVo) {
                        userUnitEvent.postValue(result)
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort("$msg")
                    }
                })
        )
    }


    /**
     * 图片上传
     */
    val uploadDataEvent: MutableLiveData<String> = MutableLiveData()
    fun uploadImage(file: File) {
        addSubscribe(
            mModel.uploadImage(file)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<String, BaseViewModel<*>>
                    (this, true) {

                    override fun onResult(result: String) {
                        Logs.d("response", result.toString())
                        uploadDataEvent.postValue(result)
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort("$msg")

                    }
                })
        )
    }

    /**
     * 修改密码
     * TODO: 0:修改密码，1:修改支付密码
     */
    val modifyEvent: SingleLiveEvent<Void> = SingleLiveEvent()

    fun modifyPwd(
        type: Int,
        phone: String,
        code: String,
        password: String
    ) {
        val dto = ModifyPwdDTO(type, phone, code, password)
        addSubscribe(
            mModel.modifyPassword(dto)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<Boolean, BaseViewModel<*>>(
                    this, true
                ) {
                    override fun onSuccess() {
                        ToastUtils.showShort("修改成功")
                        modifyEvent.call()
                    }

                    override fun onResult(result: Boolean) {

                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort("修改失败 $msg")
                    }
                })
        )
    }

    /**
     * 协议内容
     * TODO: 1-隐私政策 2-用户协议
     */
    val agreementEvent: SingleLiveEvent<AgreementVO> = SingleLiveEvent()
    fun getAgreement(id: Int) {
        addSubscribe(
            mModel.getAgreement(id.toLong())
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<AgreementVO, BaseViewModel<*>>
                    (this, false) {
                    override fun onResult(result: AgreementVO) {
                        agreementEvent.postValue(result)
                    }
                })
        )
    }

    /**
     * 获取用户信息
     */
    var userInfoDatasEvent: SingleLiveEvent<UserInfoVO> = SingleLiveEvent()
    fun getUserInfo() {
        addSubscribe(
            mModel.getUserInfo()
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<UserInfoVO, BaseViewModel<*>>
                    (this, true) {
                    override fun onResult(result: UserInfoVO) {
                        userInfoDatasEvent.postValue(result)
                        mModel.saveUserData(result)
                        mModel.saveCacheData(result)
                        mModel.saveIdentityType(result.identity)
                        mModel.setPermission(result.isPermission)
                        RouteManager.Main.intentToMain(getApplication(),
                            object : NavCallback() {
                                override fun onArrival(postcard: Postcard?) {
                                    finish()
                                }
                            })
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                    }

                    override fun onError(e: Throwable) {
                        super.onError(e)
                        ToastUtils.showShort(e.message.toString())
                    }
                })
        )
    }

    /**
     * 获取用户信息
     */
    var userInfoDataEvent: SingleLiveEvent<UserInfoVO> = SingleLiveEvent()
    fun updateUserInfo() {
        addSubscribe(
            mModel.getUserInfo()
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<UserInfoVO, BaseViewModel<*>>
                    (this, false) {

                    override fun onResult(result: UserInfoVO) {
                        Logs.d("updateUserInfo ${result.identity}")
                        userInfoDataEvent.postValue(result)
                        mModel.saveUserData(result)
                        mModel.saveCacheData(result)
                        mModel.saveIdentityType(result.identity)
                        mUI.initRefreshEvent().postValue(true)
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                        mUI.initRefreshEvent().postValue(false)
                    }

                    override fun onError(e: Throwable) {
                        super.onError(e)
                        mUI.initRefreshEvent().postValue(false)
                        ToastUtils.showShort(e.message.toString())
                    }
                })
        )
    }


    /**
     * 获取身份类型
     */
    fun getIdentityType(): Int {
        return mModel.getIdentityType()
    }


    /**
     * 获取相关数据
     */
    fun getData() {
        val observer: DisposableObserver<*> = object : CommonObserver<List<*>, BaseViewModel<*>>(
            this, true
        ) {
            override fun onResult(result: List<*>) {
                Logs.d("onResult ")
                if (result.isNotEmpty()) {
                    when (result[0]) {
                        is ProvincesVO -> {
                            Logs.d("ProvincesVO ${result.size}")
                        }
                        is UnitTypeVO -> {
                            Logs.d("UnitTypeVO ${result.size}")
                        }
                    }
                }
            }

            override fun onFailed(code: Int, msg: String?) {
                super.onFailed(code, msg)
                ToastUtils.showShort("$msg = $code")
            }
        }
        addSubscribe(
            Observable.mergeDelayError(
                mModel.queryUnitType(),
                mModel.getProvinces()
            )
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(observer as (DisposableObserver<Any>))
        )
    }


    /**
     * 联系人列表
     */
    val contactListEvent: SingleLiveEvent<List<ContactUserVo>> = SingleLiveEvent()
    fun getRongContact(name: String) {
        addSubscribe(
            mModel.getRongContact(name)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<List<ContactUserVo>, BaseViewModel<*>>
                    (this, false) {
                    override fun onResult(result: List<ContactUserVo>) {

                        contactListEvent.postValue(result)
                        dismissLoadingDialog()
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                        dismissLoadingDialog()
                    }
                })
        )
    }

    fun getRongContact(groupId: String,name: String) {
        addSubscribe(
            mModel.getRongContact(groupId,name)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<List<ContactUserVo>, BaseViewModel<*>>
                    (this, false) {
                    override fun onResult(result: List<ContactUserVo>) {

                        contactListEvent.postValue(result)
                        dismissLoadingDialog()
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                        dismissLoadingDialog()
                    }
                })
        )
    }


    /**
     * 融云其他用户信息列表
     */
    val allRongContactListEvent: SingleLiveEvent<List<ContactUserVo>> = SingleLiveEvent()
    fun getRongAllContact() {
        getServiceContact()
        addSubscribe(
            mModel.getRongAllContact()
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<List<ContactUserVo>, BaseViewModel<*>>
                    (this, false) {
                    override fun onResult(result: List<ContactUserVo>) {
                        allRongContactListEvent.postValue(result)
                        dismissLoadingDialog()
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                        dismissLoadingDialog()
                    }
                })
        )
    }

    fun getServiceContact() {
        addSubscribe(mModel.getAppServiceId()
            .compose(RxThreadHelper.rxSchedulerHelper())
            .subscribeWith(object : CommonObserver<ContactUserVo,BaseViewModel<*>>(this,true){
                override fun onResult(result: ContactUserVo) {
                    dismissLoadingDialog()
                    val userInfo = io.rong.imlib.model.UserInfo(
                        result.userUnitId.toString(),
                        result.userName,
                        Uri.parse(result.avatar)
                    )
                    RongIM.getInstance().refreshUserInfoCache(userInfo)
                }

                override fun onFailed(code: Int, msg: String?) {
                    super.onFailed(code, msg)
                    ToastUtils.showShort(msg)
                    dismissLoadingDialog()
                }

            })
        )
    }


    /**
     * 群组列表
     */
    val groupListEvent: SingleLiveEvent<List<RongGroupVO>> = SingleLiveEvent()
    fun getRongGroupList() {
        addSubscribe(
            mModel.getRongGroupList()
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<List<RongGroupVO>, BaseViewModel<*>>
                    (this, false) {
                    override fun onResult(result: List<RongGroupVO>) {
                        groupListEvent.postValue(result)
                        dismissLoadingDialog()
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                        dismissLoadingDialog()
                    }
                })
        )
    }


}